from typing import List

from common import const
from eval_lib.common.logger import get_logger
from config import conf
from common.parse_config import ParseConfig
from agent_tools.deepflow_agent.deepflow_agent import DeeepflowAgent
from agent_tools.base import AgentBase

log = get_logger()


class AgentManage():

    def __init__(self):
        self.agents: List[AgentBase] = []

    def create_agent(self, case_type=const.CASE_TYPE_CONCURRENCY) -> AgentBase:
        agent_type = conf.case_params.agent_type
        if agent_type == 'deepflowce':
            agent = DeeepflowAgent()
            if not hasattr(self, "server_meta"):
                self.server_meta = ParseConfig.get_df_server_meta(
                    case_type=case_type)
                log.info(
                    f"deploy deepflow-agent, deepflow-server meta: {self.server_meta}"
                )
            agent.init_df_server(self.server_meta)
            self.agents.append(agent)
            return agent
        else:
            # 如果没有选择有效的 agent，则记录错误
            log.error("Invalid agent type specified.")
            assert False

    def clear_all_agent(self):
        for agent in self.agents:
            agent.clear()
        self.agents = []
        agent_type = conf.case_params.agent_type
        if agent_type == 'deepflowce' and hasattr(self, "server_meta"):
            ParseConfig.release_df_env(self.server_meta.server_ip)
            log.info(f"freed df env {self.server_meta.to_json()}")
